import {useEffect, useState} from "react";
import Taro, {usePullDownRefresh} from "@tarojs/taro";
import {request} from "../../utils/request";
import {apis} from "../../constants/apis";
import {objListUnique} from "../../utils/utils";
import styles from "./Shop.module.scss"
import {Image, PageContainer, ScrollView, Swiper, SwiperItem, Text, View} from "@tarojs/components";

const Shop = () => {
  const [productList, setProductList] = useState<any>([]);
  const [selectProductId, setSelectProductId] = useState<any>(); //选择商品的ID
  const [selectProductList, setSelectProductList] = useState<any>([]); //选择商品ID数组
  const [totalPrice, setTotalPrice] = useState<any>(0); //选择商品总价格
  const [isShowCart, setShowCart] = useState(false); //是否显示购物车详情层
  const [addProductList, setAddProductList] = useState<any>([]); //商品列表详情：数量，ID，名称
  const [rankingList, setRankingList] = useState<any>([]); //宣传商品
  const goOrderSubmit = () => {
    if (selectProductList.length === 0) return
    Taro.navigateTo({
      url: `../order_submit/order_submit?selectProductList=${selectProductList.toString()}`
    })
  }
  useEffect(() => {
    getProductList();
    getRankingList();
  }, []);

  usePullDownRefresh(() => {
    getProductList();
    setTimeout(() => {
      Taro.stopPullDownRefresh();
    }, 1000);
  })

  const getProductList = () => {
    Taro.showLoading({title: '加载中'})
    request({
      url: apis.PRODUCT_LIST,
      method: "GET",
    }).then(res => {
      let list: any = [];
      res.forEach(item => {
        list = list.concat(item.products);
      })
      const addProductList: any = [];
      list.forEach(item => {
        const addProduct = {
          id: item.id,
          name: item.name,
          num: 0,
          price: item.price,
        }
        addProductList.push(addProduct);
      })
      setAddProductList(addProductList);
      setProductList(res);
      Taro.hideLoading();
    })
  };

  const getRankingList = () => {
    request({
      url: apis.GET_RANK_LIST,
      data: {
        time: "MONTH",
      },
      pureData: false,
    }).then(res => {
      if (res.code === 200) {
        setRankingList(res.data);
      }
    })
  }

  const addProduct = (product) => {
    const list = selectProductList;
    list.push(product.id || product.id); //支持适配从购物车里加入商品
    setSelectProductList(list);
    if (product.price) {
      setTotalPrice(product.price + totalPrice);
    } else {
      setTotalPrice(product.price + totalPrice);
    }
    addProductList.forEach(item => {
      if (product.product_id === item.id || product.id === item.id) {
        const addProduct = {
          id: item.id,
          name: item.name,
          num: ++item.num,
          price: item.price,
        }
        let list = addProductList.concat(addProduct);
        setAddProductList(objListUnique(list));
      }
    })
  }

  const reduceProduct = (product) => {
    let list = selectProductList;
    const res: any = [];
    for (let i = 0; i < list.length; i++) {
      if (product.id === list[i] || product.id === list[i]) {
        continue;
      } else {
        res.push(list[i]);
      }
    }
    setSelectProductList(res);
    if (product.price) {
      setTotalPrice(product.price + totalPrice);
    } else {
      setTotalPrice(product.price + totalPrice);
    }
    addProductList.forEach(item => {
      if (product.product_id === item.id || product.id === item.id) {
        let addProduct = {
          id: item.id,
          name: item.name,
          num: item.num === 0 ? 0 : item.num--,
          price: item.price,
        }
        let list = addProductList.concat(addProduct);
        setAddProductList(objListUnique(list));
      }
    })
  }

  const isShowAdd = (id) => {
    if (addProductList.length <= 0) return true;
    return addProductList.filter(function (elm) {
      return (elm.id === id && elm.num === 0);
    }).length > 0
  }


  const showCart = () => {
    if (selectProductList.length > 0) {
      setShowCart(true)
    }
  }

  const showProductNum = (id) => {
    if (addProductList.length <= 0) return;
    let res = addProductList.filter(elm => {
      return elm.id === id;
    })
    if(res.length===0)return;
    return res[0].num;
  }

  const btnClearAll = () => {
    setShowCart(false);
    //console.log(addProductList, selectProductList);
    setAddProductList([]);
    let list = addProductList;
    list.forEach(item => {
      item.num = 0;
    })
    setSelectProductList([]);
    setAddProductList(list);
    setTotalPrice(0)
  };

  const clickScrollItem = (item) => {
    setSelectProductId('a' + item.typeId)
  }

  const toProductOrderDetail = (product) => {
    let data = JSON.stringify(product)
    Taro.navigateTo({
      url: `../product_detail/product_detail?data=${encodeURIComponent(data)}`,
    })
  }

  return (
    <View className="container">
      <View className={styles.main_header}>
        <Text className="text_medium">餐厅名称</Text>
        <Text style={{marginTop: '10rpx'}} className="text_small">公告：欢迎光临本店，很高兴为您服务。</Text>
      </View>

      <Swiper
        className={styles.main_swiper}
        autoplay={true}
        circular
        indicatorDots
        indicatorColor='#999'
        indicatorActiveColor='#333'>
        {rankingList.map(item => {
          return (
            <SwiperItem className={styles.swiper_item}>
              <Image style={{width: "100vw"}} src={item.image}/>
            </SwiperItem>
          )
        })}
      </Swiper>

      <View className={styles.order}>点单</View>
      <View style={{height: "60%", display: "flex", marginTop: "30rpx"}}>
        {/*左边导航栏*/}
        <ScrollView scrollY={true}
                    className={`${styles.order_list_nav_bar} ${styles.scroll_view_left}`}>
          {productList.map(item => {
            return (
              <View onClick={() => {
                clickScrollItem(item)
              }}
                    className={styles.left_item}
                    style={{backgroundColor: 'a' + item.typeId === selectProductId ? 'white' : '#F2F3F0'}}>{item.type}</View>
            )
          })}
        </ScrollView>

        {/*右边导航栏*/}
        {/*scrollIntoView只能以字母开头*/}
        <ScrollView scrollIntoView={selectProductId} className={styles.right} scrollY={true}>
          {productList.map(item => {
            return (
              <View id={'a' + item.typeId} style={{marginTop: "20rpx"}}>
                <View className="text-bold text-medium">{item.type}</View>
                {item.products.map(item => {
                  return (
                    <View style={{display: "flex", marginTop: "40rpx"}}>
                      <Image onClick={() => {
                        toProductOrderDetail(item)
                      }} style={{width: "150rpx", height: "150rpx"}}
                             src={item.imagePath === '' || item.imagePath === null ? require("../../assets/shoppingcart.png") : item.imagePath}/>
                      <View style={{display: "flex", flexDirection: "column"}}>
                        <Text style={{fontWeight: "bold"}}>{item.name}</Text>
                        <View className={styles.display_row}>
                          <Text style={{width: "60rpx"}}>￥{item.price}</Text>
                          {isShowAdd(item.id) &&
                          <Image onClick={() => {
                            addProduct(item)
                          }} style={{
                            width: "50rpx",
                            height: "50rpx",
                            marginLeft: "250rpx"
                          }} src={require("../../assets/addshop.png")}/>
                          }

                          {!isShowAdd(item.id) &&
                          <View style={{marginLeft: "130rpx"}} className={styles.control_shop_num}>
                            <Image style={{
                              width: "45rpx",
                              height: "45rpx",
                              marginTop: "4rpx"
                            }} onClick={() => {
                              reduceProduct(item);
                            }} src={require("../../assets/reduceShop.png")}/>
                            <Text className={styles.shop_num}>{showProductNum(item.id)}</Text>
                            <Image onClick={() => {
                              addProduct(item)
                            }} style={{
                              width: "50rpx",
                              height: "50rpx",
                            }} src={require("../../assets/addshop.png")}/>
                          </View>
                          }
                        </View>
                      </View>
                    </View>
                  )
                })}
              </View>
            )
          })}
        </ScrollView>
      </View>

      <View className={styles.go}>
        <View style={{display: "flex"}}>
          <View onClick={showCart} style={{display: "flex"}}>
            <Image style={{opacity: selectProductList.length > 0 ? 1 : 0.6}} className={styles.shop_cart_style}
                   src={require("../../assets/shoppingcart.png")}/>
            <View style={{visibility: selectProductList.length > 0 ? 'visible' : 'hidden'}}
                  className={styles.product_num}>
              {selectProductList.length}
            </View>
          </View>

          <View style={{display: selectProductList.length > 0 ? 'block' : 'none'}}
                className="text_total_price">￥{totalPrice}</View>
        </View>
        <View style={{opacity: selectProductList.length > 0 ? 1 : 0.6}} className={styles.btn_go}
              onClick={goOrderSubmit}>
          去结算
        </View>

      </View>
      <PageContainer customStyle={'marginBottom: 20%'} zIndex={101} show={isShowCart} onClickOverlay={() => {
        setShowCart(false);
      }}>
        <View className={styles.page_container}>
          <View className={styles.page_container_header}>
            <Text>已选商品</Text>
            <View onClick={btnClearAll} style={{display: 'flex'}}>
              <Image style={{width: "32rpx", height: "32rpx"}} src={require("../../assets/rubbish.png")}/>
              <Text>清空</Text>
            </View>
          </View>

          <View style={{marginTop: "10rpx", marginBottom: "10rpx"}} className="divide-1-dark"/>

          <ScrollView scrollY={true} className={styles.page_container_body}>
            {addProductList.map((item, index) => {
              if (item.num !== 0) {
                return (
                  <View>
                    <View style={{display: "flex", marginTop: "40rpx"}}>
                      <Image style={{width: "150rpx", height: "150rpx"}}
                             src={require("../../assets/shoppingcart.png")}/>
                      <View style={{display: "flex", flexDirection: "column"}}>
                        <Text style={{fontWeight: "bold"}}>{item.name}</Text>
                        <View className={styles.display_row}>
                          <Text style={{width: "60rpx", color: "red"}}>￥{item.num * item.price}</Text>
                          {!isShowAdd(item.id) &&
                          <View style={{marginLeft: "270rpx"}} className={styles.control_shop_num}>
                            <Image style={{
                              width: "45rpx",
                              height: "45rpx",
                              marginTop: "4rpx"
                            }} onClick={() => {
                              reduceProduct(item);
                            }} src={require("../../assets/reduceShop.png")}/>
                            <Text className={styles.shop_num}>{showProductNum(item.id)}</Text>
                            <Image onClick={() => {
                              addProduct(item)
                            }} style={{
                              width: "50rpx",
                              height: "50rpx",
                            }} src={require("../../assets/addshop.png")}/>
                          </View>
                          }
                        </View>
                      </View>
                    </View>
                    <View style={{display: index !== addProductList.length - 1 ? 'block' : 'none'}}
                          className="divide-1-dark"/>
                  </View>
                )
              }
            })}
          </ScrollView>
        </View>
      </PageContainer>
    </View>
  )
};
export default Shop;
